<template>
  <el-button
    v-if="hasPermission"
    v-bind="$attrs"
    :disabled="disabled || !hasPermission"
    @click="handleClick"
  >
    <slot />
  </el-button>
  <el-tooltip
    v-else
    :content="tooltipContent"
    placement="top"
  >
    <el-button
      v-bind="$attrs"
      disabled
      @click.prevent
    >
      <slot />
    </el-button>
  </el-tooltip>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import permissionService from '@/services/permission.service'

interface Props {
  permission: string | string[]
  tooltip?: string
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  tooltip: '',
  disabled: false
})

const emit = defineEmits<{
  click: [event: MouseEvent]
}>()

const { t } = useI18n()

// 检查权限
const hasPermission = computed(() => {
  if (Array.isArray(props.permission)) {
    return permissionService.hasAnyPermission(props.permission)
  }
  return permissionService.hasPermission(props.permission)
})

// 提示内容
const tooltipContent = computed(() => {
  if (props.tooltip) {
    return props.tooltip
  }

  if (Array.isArray(props.permission)) {
    return t('AbpUi.NoPermissionForAction', { permissions: props.permission.join(', ') })
  }

  return t('AbpUi.NoPermissionForAction', { permissions: props.permission })
})

// 处理点击事件
const handleClick = (event: MouseEvent) => {
  if (hasPermission.value && !props.disabled) {
    emit('click', event)
  }
}
</script>

<style scoped>
/* ABP风格的权限按钮样式 */
.el-button[disabled] {
  cursor: not-allowed;
  opacity: 0.6;
}
</style>